package com.greatwqs.wmall.common.provider.controller;

import org.apache.dubbo.rpc.model.ApplicationModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;

import lombok.extern.slf4j.Slf4j;

/**
 * NACOS 服务优雅下线
 *
 * @author wang-qingsong
 * @since 2025-06-08
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/internal/nacos")
public class NacosController {

    @Autowired
    private NacosAutoServiceRegistration nacosAutoServiceRegistration;

    @PostMapping(value = "deregister")
    public void deregister() {
        log.warn("NacosController internal deregister start!");
        deregisterSpringCloud();
        // dubbo 不需要手动注销
        // deregisterDubbo();
        log.warn("NacosController internal deregister finished!");
    }

    private void deregisterSpringCloud() {
        try {
            nacosAutoServiceRegistration.destroy();
            log.warn("NACOS deregisterSpringCloud done!");
        } catch (Exception e) {
            log.error("NACOS deregisterSpringCloud error", e);
        }
    }

    /**
     * Dubbo 服务优雅下线
     * <a href="https://dubbo-next.staged.apache.org/zh-cn/overview/mannual/java-sdk/tutorial/graceful-shutdown/">...</a>
     */
    private void deregisterDubbo() {
        try {
            ApplicationModel.defaultModel().destroy();
            log.warn("NACOS deregisterDubbo done!");
        } catch (Exception e) {
            log.error("NACOS deregisterDubbo error", e);
        }
    }
}